<?php

namespace App\Models;

use App\Http\Resources\ApiCategory;
use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    public $timestamps = false;

    protected static function boot()
    {
        parent::boot();
        // 监听模型创建事件，在写入数据库之前触发
        static::creating(function ($model) {
            if ($model->parent_id) {
                $model->path = $model->getChildPath();
            } else {
                $model->path = "0,";
                $model->parent_id = 0;
            }
        });

        static::updating(function ($model) {
            if ($model->parent_id) {
                $model->path = $model->getChildPath();
            } else {
                $model->path = "0,";
                $model->parent_id = 0;
            }
        });
    }

    public function format()
    {
        return ApiCategory::make($this);
    }

    public function products()
    {
        return $this->hasMany(Product::class);
    }

    public function parent()
    {
        return $this->belongsTo(Category::class, "parent_id");
    }

    public function children()
    {
        return $this->hasMany(Category::class, "parent_id");
    }

    public function getChildPath()
    {
        return $this->parent->path . $this->parent->id . ",";
    }
}
